//格式化时间
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 
function formatSubscribeTime(cellValue, options, rowObject) {
	var dateStr = "";
	if(cellValue){
		var crtTime = new Date(cellValue);
		dateStr = dateFtt("yyyy-MM-dd hh:mm:ss",crtTime);
	}
    return dateStr;
}
//加载字典
function dictJudge(value, options, row){
    //sex为自定义字典项
	var statusObj = vm.options.sex;
    for( var i=0;i< statusObj.length;i++ ){
        if(statusObj[i].value == value){
            return '<span>'+statusObj[i].text+'</span>' ;
        }
    }
}
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'demo/goods/list',
        datatype: "json",
        colModel: [			
			{ label: 'goodsId', name: 'goodsId', index: 'goods_id', width: 50, key: true },
			{ label: '商品名', name: 'name', index: 'name', width: 80 }, 			
			{ label: '介绍', name: 'intro', index: 'intro', width: 80 }, 			
			{ label: '价格', name: 'price', index: 'price', width: 80 }, 			
			{ label: '数量', name: 'num', index: 'num', width: 80 }			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 100,
		rowList : [50,100,200],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            //设置grid高度  减去占用的高度
            $(window).on('resize', function() {
                $("#jqGrid").setGridHeight($(window).height()-430);
            }).resize();
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		goods: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			// vm.showList = false;
            $('#myModal').modal({
                keyboard: true
            });
			vm.title = "新增";
			vm.goods = {};
		},
		update: function (event) {
			var goodsId = getSelectedRow();
			if(goodsId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(goodsId)
		},
		saveOrUpdate: function (event) {
			var url = vm.goods.goodsId == null ? "demo/goods/save" : "demo/goods/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.goods),
			    success: function(r){
			    	if(r.code === 0){
						// alert('操作成功', function(index){
                        $('#myModal').modal('hide');
                        vm.reload();
						// });
					}else{
						alert(r.msg);
					}
				}
			});
		},
        exportExcel: function (event) {
            var fileObj = document.getElementById("upload").files[0]; // js 获取文件对象
            if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                alert("请选择文件");
                return;
            }
            var formFile = new FormData();
            formFile.append("file", fileObj); //加入文件对象
            $.ajax({
                url: baseURL + "demo/goods/exportExcel",
                data: formFile,
                type: "POST",
                dataType: "json",
                cache: false,//上传文件无需缓存
                processData: false,//用于对data参数进行序列化处理 这里必须false
                contentType: false, //必须
                success: function (result) {
                    console.log(result);
                    if(result.msg == 'success'){
                        alert("上传成功!");
                        vm.reload();
                    }else{
                        alert(result.msg);
                    }
                },
            });
            //清空input file 内容
            $("#upload").val('');
        },
		del: function (event) {
			var goodsIds = getSelectedRows();
			if(goodsIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "demo/goods/delete",
                    contentType: "application/json",
				    data: JSON.stringify(goodsIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
                                echartData();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(goodsId){
			$.get(baseURL + "demo/goods/info/"+goodsId, function(r){
                vm.goods = r.goods;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
            echartData();
		}
	}
});


var mychart = echarts.init(document.getElementById("myChart"));

function echartData(){
    //获取柱状图数据
    $.ajax({
        type: "POST",
        cache: false,
        url: baseURL + "/demo/goods/getChartList?_" + $.now(),
        dataType: "json",
        data:{
            limit:100
        },
        error: function () {
            console.error('获取商品数据失败!');
            alert("系统异常");
            return;
        },
        success: function (result) {
            if(!result.data.xAxisData){
                alert("无数据，请先导入数据");
            }
            var option = {
                backgroundColor: '#ffffff',//背景色
                title: {
                    text:'商品价格',
                    x:'center',
                    y:'top',
                    textStyle:{
                        color:'#000000'
                    }
                },
                tooltip: {},
                // legend: {
                //     data:['用电量']
                // },
                textStyle:{
                    color:'#000000'
                    // fontSize:18
                },
                xAxis: {
                    type: 'category',
                    // data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                    data: result.data.xAxisData
                },
                yAxis: {
                    type: 'value',
                    name: '用电量'
                },
                series: [
                    {
                        name:'价格',
                        type: 'bar',
                        // data: [120.33, 200.4, 150.4, 80, 70, 310, 535,650.4, 500, 420, 210, 130],
                        data: result.data.seriesPriceData
                    },
                    {
                        name:'价格',
                        type: 'line',
                        data: result.data.seriesPriceData
                    }
                    // ,
                    // {
                    //     name:'数量',
                    //     type: 'bar',
                    //     data: result.data.seriesNumData
                    // }
                ]
            };
            mychart.setOption(option);
        }
    });
}